<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/utils/request'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ManageSelect from './ManageSelect.vue'
import {
  artPublishService,
  artDetailServicr,
  artEditService
} from '@/api/article'
import axios from 'axios'

const drawer = ref(false)
const imgUrl = ref('')
const editorRef = ref()
const form = ref()
const defaultForm = {
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
}
const artForm = ref({ ...defaultForm })

const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  cover_img: [{ required: true, message: '请添加文章封面', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}
const open = async (row) => {
  drawer.value = true
  if (row.id) {
    // 编辑
    const res = await artDetailServicr(row.id)
    artForm.value = res.data.data
    // 获取的封面图片不包含基地址
    imgUrl.value = baseURL + res.data.data.cover_img

    const file = imageUrlToFile(imgUrl.value, res.data.data.cover_img)
    artForm.value.cover_img = file
  } else {
    // 发布
    artForm.value = { ...defaultForm }
    imgUrl.value = ''
    editorRef.value.setHTML('')
  }
}

const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  artForm.value.cover_img = uploadFile.raw
}

const emit = defineEmits(['success'])
const onPublish = async (state) => {
  await form.value.validate()
  artForm.value.state = state
  const fd = new FormData()
  // 转换 formData 数据，请求数据需求
  for (let key in artForm.value) {
    fd.append(key, artForm.value[key])
  }
  if (artForm.value.id) {
    await artEditService(fd)
    ElMessage.success('修改成功')
    drawer.value = false
    emit('success', 'edit')
  } else {
    // 添加请求
    await artPublishService(fd)
    ElMessage.success('添加成功')
    drawer.value = false
    emit('success', 'add')
  }
}

const imageUrlToFile = (imageUrl, fileName) => {
  return new Promise((resolve, reject) => {
    axios
      .get(imageUrl, {
        responseType: 'blob'
      })
      .then((response) => {
        // Blob响应数据转换为File对象
        const file = new File([response.data], fileName, {
          type: response.headers['content-type']
        })
        resolve(file)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

defineExpose({
  open
})
</script>
<template>
  <el-drawer
    v-model="drawer"
    title="添加文章"
    size="50%"
    :direction="direction"
    before-close
  >
    <el-form :model="artForm" :rules="rules" ref="form">
      <el-form-item prop="title" label="文章标题" label-width="100px">
        <el-input v-model="artForm.title" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="cate_id" label="文章分类" label-width="100px">
        <ManageSelect v-model="artForm.cate_id"></ManageSelect>
      </el-form-item>
      <el-form-item prop="cover_img" label="文章封面" label-width="100px">
        <el-upload
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
          class="avatar-uploader"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="content" label="文章内容" label-width="100px">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="artForm.content"
            contentType="html"
            ref="editorRef"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style scoped>
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: blue;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
/* .editor {
  height: 200px;
} */
</style>
